<template>
	<div class="node-wrap">
		<div class="node-wrap-box" @click="show">
			<div class="node-wrap-box-title" :style="{background: nodeConfig.color}">
				<i class="icon el-icon-user-solid"></i>
				<span>{{ nodeConfig.nodeName }}</span>
				<i class="close el-icon-close" v-if="!disabled" @click.stop="delNode()"></i>
			</div>
			<div class="content">
				<!-- <span v-if="toText(nodeConfig)">{{ toText(nodeConfig) }}</span>
        <span v-else class="placeholder">请选择</span> -->
        <span v-if="nodeConfig.nodeDescription">{{nodeConfig.nodeDescription}}</span>
        <span v-else-if="toText(nodeConfig)">{{ toText(nodeConfig) }}</span>
        <span v-else class="placeholder">请选择</span>
        <img v-show="showCompleteIcon && nodeConfig.complete" class="node-pass-icon" src="../../../assets/pass.png" alt="">
			</div>
      <div class="wh-node-operation" v-if="nodeConfig.dealButtonNames && nodeConfig.dealButtonNames.length>0">
        <p class="wh-node-des">操作按钮：</p>
        <div class="wh-node-btns">
          <el-tag type="info" style="margin-right: 5px; margin-bottom: 5px;" size="mini" v-for="(item, index) in nodeConfig.dealButtonNames" :key="index">{{item}}</el-tag>
        </div>
      </div>
		</div>
		<add-node :parentNodeId="nodeConfig.nodeId" :base-url="baseUrl" :headers="headers" v-model="nodeConfig.childNode" :disabled="disabled"></add-node>
		<el-drawer title="审批人设置" :visible.sync="drawer" destroy-on-close append-to-body :size="500">
			<template #title>
				<div class="node-wrap-drawer__title">
					<label @click="editTitle" v-if="!isEditTitle">{{form.nodeName}}<i class="node-wrap-drawer__title-edit el-icon-edit"></i></label>
					<el-input v-if="isEditTitle" ref="nodeTitle" v-model="form.nodeName" clearable @blur="saveTitle" @keyup.enter="saveTitle"></el-input>
				</div>
			</template>
			<el-container>
				<el-main style="padding:0 20px 20px 20px">
					<el-form label-position="top">
            <el-form-item label="节点描述">
            	<el-input v-model="form.nodeDescription" placeholder="请输入节点描述"></el-input>
            </el-form-item>
            <el-form-item label="卡片顶部颜色">
            	<el-color-picker v-model="form.color"></el-color-picker>
            </el-form-item>
            <el-form-item label="操作">
              <el-select v-model="form.dealButtons" multiple placeholder="请选择">
                <el-option
                  v-for="item in dealList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
						<el-form-item label="审批人员类型">
							<el-select v-model="form.setType">
								<el-option :value="1" label="指定成员"></el-option>
								<el-option :value="2" label="主管"></el-option>
								<el-option :value="3" label="角色"></el-option>
								<el-option :value="4" label="发起人自选"></el-option>
								<el-option :value="5" label="发起人自己"></el-option>
								<el-option :value="7" label="连续多级主管"></el-option>
                <el-option :value="8" label="上一步执行人"></el-option>
                <el-option :value="9" label="自定义"></el-option>
							</el-select>
						</el-form-item>
						<el-form-item v-if="form.setType==1" label="选择成员">
							<el-button type="primary" icon="el-icon-plus" round @click="selectHandle(1, form.nodeUserList)">选择人员</el-button>
							<div class="tags-list">
								<el-tag v-for="(user, index) in form.nodeUserList" :key="user.id" closable @close="delUser(index)">{{user.name}}</el-tag>
							</div>
						</el-form-item>
            <el-form-item v-if="form.setType==9" label="自定义内容">
              <template slot="label">
                <span>自定义内容&nbsp;</span>
                <el-tooltip content="格式为类名(bean).方法名" placement="top">
                  <i class="el-icon-question" style="font-size: 16px;"></i>
                </el-tooltip>
              </template>
            	<el-input v-model="form.nodeUserCustom" placeholder="请输入自定义内容" />
            </el-form-item>
						<el-form-item v-if="form.setType==2" label="指定主管">
							发起人的第  <el-input-number v-model="form.examineLevel" :min="1"/>  级主管
						</el-form-item>

						<el-form-item v-if="form.setType==3" label="选择角色">
							<el-button type="primary" icon="el-icon-plus" round @click="selectHandle(2, form.nodeRoleList)">选择角色</el-button>
							<div class="tags-list">
								<el-tag v-for="(role, index) in form.nodeRoleList" :key="role.id" type="info" closable @close="delRole(index)">{{role.name}}</el-tag>
							</div>
						</el-form-item>

						<el-form-item v-if="form.setType==4" label="发起人自选">
							<el-radio-group v-model="form.selectMode">
								<el-radio :label="1">自选一个人</el-radio>
								<el-radio :label="2">自选多个人</el-radio>
							</el-radio-group>
						</el-form-item>

						<el-form-item v-if="form.setType==7" label="连续主管审批终点">
							<el-radio-group v-model="form.directorMode">
								<el-radio :label="0">直到最上层主管</el-radio>
								<el-radio :label="1">自定义审批终点</el-radio>
							</el-radio-group>
							<p v-if="form.directorMode==1">直到发起人的第  <el-input-number v-model="form.directorLevel" :min="1"/> 级主管</p>
						</el-form-item>

						<el-divider></el-divider>
						<el-form-item label="">
							<el-checkbox v-model="form.termAuto" label="超时自动审批"></el-checkbox>
						</el-form-item>
						<template v-if="form.termAuto">
							<el-form-item label="审批期限（为 0 则不生效）">
								<el-input-number v-model="form.term" :min="0"/> 小时
							</el-form-item>
							<el-form-item label="审批期限超时后执行">
								<el-radio-group v-model="form.termMode">
									<el-radio :label="0">自动通过</el-radio>
									<el-radio :label="1">自动拒绝</el-radio>
								</el-radio-group>
							</el-form-item>
						</template>
						<el-divider></el-divider>
						<el-form-item label="多人审批时审批方式">
							<el-radio-group v-model="form.examineMode">
								<p style="width: 100%;padding: 5px 0;"><el-radio :label="1">按顺序依次审批</el-radio></p>
								<p style="width: 100%;padding: 5px 0;"><el-radio :label="2">会签 (可同时审批，每个人必须审批通过)</el-radio></p>
								<p style="width: 100%;padding: 5px 0;"><el-radio :label="3">或签 (有一人审批通过即可)</el-radio></p>
							</el-radio-group>
						</el-form-item>
            <el-form-item label="驳回模式">
            	<el-radio-group v-model="form.rejectModel.rejectMode">
            		<el-radio :label="1">直接结束</el-radio>
            		<el-radio :label="2">拨回到指定节点</el-radio>
            	</el-radio-group>
            </el-form-item>
            <el-form-item label="驳回到指定节点" v-show="form.rejectModel.rejectMode === 2">
              <el-select v-model="form.rejectModel.returnNodeId" placeholder="请选择节点">
                <el-option v-for="(item, index) in rejectNodeList" :key="index" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
					</el-form>
				</el-main>
				<el-footer>
					<el-button type="primary" @click="save">保存</el-button>
					<el-button @click="cancel">取消</el-button>
				</el-footer>
			</el-container>
		</el-drawer>
	</div>
</template>

<script>
	import addNode from './addNode.vue'
  import {
    flowButtonList
  } from '../../../network/api.js'
import { Tree } from 'element-ui'
	export default {
		inject: ['select', 'getRootConfig'],
		props: {
			value: { type: Object, default: () => {} },
      disabled: {
        type: Boolean,
        default: false
      },
      baseUrl: {
        type: String,
        default: ''
      },
      headers: {
        type: Object,
        default: () => {
          return {}
        }
      },
      showCompleteIcon: {
        type: Boolean,
        default: false
      }
		},
		components: {
			addNode
		},
		data() {
			return {
				nodeConfig: {},
				drawer: false,
				isEditTitle: false,
				form: {
          rejectModel: {
            rejectMode: 0,
            returnNodeId: ''
          }
        },
        dealList: [],
        rejectNodeList: []
			}
		},
		watch:{
			value(){
				this.nodeConfig = this.value
			}
		},
		mounted() {
			this.nodeConfig = this.value
      if (this.dealList.length === 0) {
        this.initDealData()
      }
		},
		methods: {
			show(){
        if (this.disabled) return
        this.getRootConfig().then(res => {
          const newTreeData = this.removeNodeById([JSON.parse(JSON.stringify(res))], this.nodeConfig.parentNodeId)
          this.rejectNodeList = this.initRejectNodeList(newTreeData, [])
        })
				this.form = {}
				this.form = JSON.parse(JSON.stringify(this.nodeConfig))
				this.drawer = true
			},
      removeNodeById (treeData, targetId) {
        if (!Array.isArray(treeData)) return treeData; // 确保输入参数是数组类型
        for (let i = 0; i < treeData.length; i++) {
          const node = treeData[i];
          if (node.nodeId === targetId) {
              delete treeData[i].childNode; // 删除目标节点
          } else if (node.childNode || (treeData[i].conditionNodes && treeData[i].conditionNodes.length>0)) {
              var newArr = []
              if (treeData[i].conditionNodes && treeData[i].conditionNodes.length>0) {
                newArr = newArr.concat(treeData[i].conditionNodes)
              }
              var lookNext = true
              for (var j = 0; j < newArr.length; j++) {
                if (newArr[j].nodeId === targetId) {
                  lookNext = false
                  delete treeData[i].childNode; // 删除目标节点
                  break
                }
              }
              if (treeData[i].childNode && lookNext) {
                newArr = newArr.concat([treeData[i].childNode])
              }
              this.removeNodeById(newArr, targetId); // 递归处理子节点
          }
        }
        return treeData;
      },
      initDealData () {
        flowButtonList(this.baseUrl, this.headers, {}).then(res => {
          if (res.code=== 200) {
            this.dealList = res.data
          }
        })
      },
      initRejectNodeList (arr, result) {
        for (var i = 0; i < arr.length; i++) {
          if (arr[i].type === 0 || arr[i].type === 1) {
            result.push({
              value: arr[i].nodeId,
              label: arr[i].nodeName
            })
          }
          if (arr[i].childNode || (arr[i].conditionNodes && arr[i].conditionNodes.length>0)) {
            var newArr = []
            if (arr[i].childNode) {
              newArr = newArr.concat([arr[i].childNode])
            }
            if (arr[i].conditionNodes && arr[i].conditionNodes.length>0) {
              newArr = newArr.concat(arr[i].conditionNodes)
            }

            this.initRejectNodeList(newArr, result)
          }
        }
        return result
      },
			editTitle(){
				this.isEditTitle = true
				this.$nextTick(()=>{
					this.$refs.nodeTitle.focus()
				})
			},
			saveTitle(){
				this.isEditTitle = false
			},
			save(){
        if (this.form.setType === 1) {
          this.form.nodeRoleList = []
        } else if (this.form.setType === 3) {
          this.form.nodeUserList = []
        } else {
          this.form.nodeRoleList = []
          this.form.nodeUserList = []
        }
        if (this.form.rejectModel.rejectMode === 1) {
          this.form.rejectModel.returnNodeId = ''
        }
        var arr = []
        this.form.dealButtons.forEach(ele => {
          let obj = this.dealList.find(e => e.id === ele)
          if (obj) {
            arr.push(obj.name)
          }
        })
        this.form.dealButton = this.form.dealButtons.join(',')
        this.form.dealButtonNames = arr
				this.$emit("input", this.form)
				this.drawer = false
			},
      cancel () {
        this.drawer = false
      },
			delNode(){
				this.$emit("input", this.nodeConfig.childNode)
			},
			delUser(index){
				this.form.nodeUserList.splice(index, 1)
			},
			delRole(index){
				this.form.nodeRoleList.splice(index, 1)
			},
			selectHandle(type, data){
				this.select(type, data)
			},
			toText(nodeConfig){
				if(nodeConfig.setType == 1){
					if (nodeConfig.nodeUserList && nodeConfig.nodeUserList.length>0) {
						const users = nodeConfig.nodeUserList.map(item=>item.name).join("、")
						return users
					}else{
						return false
					}
				}else if (nodeConfig.setType == 2) {
					return nodeConfig.examineLevel == 1 ? '直接主管' : `发起人的第${nodeConfig.examineLevel}级主管`
				}else if (nodeConfig.setType == 3) {
					if (nodeConfig.nodeRoleList && nodeConfig.nodeRoleList.length>0) {
						const roles = nodeConfig.nodeRoleList.map(item=>item.name).join("、")
						return '角色-' + roles
					}else{
						return false
					}
				}else if (nodeConfig.setType == 4) {
					return "发起人自选"
				}else if (nodeConfig.setType == 5) {
					return "发起人自己"
				}else if (nodeConfig.setType == 7) {
					return "连续多级主管"
				} else if (nodeConfig.setType === 9) {
          return "自定义内容"
        }
			}
		}
	}
</script>


